package com.example.wwk.graduationpractice.Fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.example.wwk.graduationpractice.Activity.LoginActivity;
import com.example.wwk.graduationpractice.AsyncTask.PsychologyListAsyncTask;
import com.example.wwk.graduationpractice.Adapter.PsychologyAdapter;
import com.example.wwk.graduationpractice.Bean.ComeMsgBean;
import com.example.wwk.graduationpractice.Bean.PsychologistBean;
import com.example.wwk.graduationpractice.Broadcast.MessageComeBroadReceiver;
import com.example.wwk.graduationpractice.Broadcast.NotifyComeBroadReceiver;
import com.example.wwk.graduationpractice.Globalutils.CustomDialogUtils;
import com.example.wwk.graduationpractice.Globalutils.DividerItemDecorationUtils;
import com.example.wwk.graduationpractice.Globalutils.MyApplication;
import com.example.wwk.graduationpractice.Globalutils.PromptShowUtils;
import com.example.wwk.graduationpractice.NetDataUtils.LitePalUtils;
import com.example.wwk.graduationpractice.R;
import com.example.wwk.graduationpractice.SmackUtils.ChatListenerUtils;
import com.example.wwk.graduationpractice.SmackUtils.RosterUtils;
import com.example.wwk.graduationpractice.UnreadBubble.BounceCircle;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.roster.Roster;
import org.jivesoftware.smack.roster.RosterEntry;
import org.jivesoftware.smack.roster.RosterListener;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by wwk on 2017/4/24.
 */

public class tab_message extends Fragment {
    private Context context;
    private SwipeRefreshLayout swipeRefresh;
    private PsychologyAdapter adapter;
    private RecyclerView recyclerView;
    //广播监听服务器消息
//    private NotifyComeBroadReceiver notifyComeBroadReceiver;
    private IntentFilter intentFilter;
    //处理未读消息的显示
    private DealUnreadBroadReceiver dealUnreadBroadReceiver;
    //监听chat到来的消息
    private MessageComeBroadReceiver messageComeBroadReceiver;
    private ChatManager chatManager;
    //smack
    private AbstractXMPPConnection connection;
    private List<PsychologistBean> psychologists = new ArrayList<>();
    private Roster roster;
    private List<RosterEntry> entries;
    private static final String DOCTORGROUP = "doctor";
    private static final String USERGROUP = "user";
    private static String groupName;
    //
    private CustomDialogUtils progressDialog;
    //未读消息气泡
    private BounceCircle circle;
    public static boolean isTouchable = true; // 是否响应按键事件，如果一个气泡已经在响应，其它气泡就不响应，同一界面始终最多只有一个气泡响应按键
    //
    private static String thisuserName;
    private static int identity;
    private String TAG = "123";
    //handler
    private static final int GET_PRESHENCE = 990;
    private static final int ONREFRESH = 991;
    private static final int UnreadBubble = 992;
    private static final int UnreadBroadReceiver = 993;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_PRESHENCE:
                    adapter.notifyDataSetChanged();
                    break;
                case ONREFRESH:
                    adapter.notifyDataSetChanged();
                    new Handler().postDelayed(new Runnable() {     //Handler实现延迟刷新UI
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                            swipeRefresh.setRefreshing(false);
                            PromptShowUtils.showSnackbar(swipeRefresh, "刷新成功！");
                        }
                    }, 5000);        //秒
                    break;
                case UnreadBubble:
                    int pos = msg.arg1;
                    adapter.notifyItemChanged(pos);
                    break;
                case UnreadBroadReceiver:
                    adapter.notifyDataSetChanged();
                    break;

            }
        }
    };

    public static tab_message newInstance(String thisuserName2, int identity2) {
        tab_message fragment = new tab_message();
        thisuserName = thisuserName2;
        identity = identity2;
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab_message, container, false);
        //加载对话框
        progressDialog = new CustomDialogUtils(context, R.style.CustomDialog);
        progressDialog.setCancelable(false);        //无法手动取消
        progressDialog.show();
        //swipe刷新
        swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.psychologist_list_swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
        swipeRefresh.setOnRefreshListener(new MyRefreshListener());
        //roster
        //身份识别，加载不同的用户列表
        if (identity == LoginActivity.USER)
            groupName = DOCTORGROUP;
        else if (identity == LoginActivity.DOCTOR)
            groupName = USERGROUP;
        connection = MyApplication.getConnection();   //获取全局连接
        try {
            roster = RosterUtils.getRoster(connection);
            entries = RosterUtils.getEntriesByGroup(roster, groupName);

        } catch (NullPointerException e) {
            e.printStackTrace();
            PromptShowUtils.showDialog("警告", "网络不可达，请检查网络状态!", context);
        }

        //未读消息气泡
        circle = (BounceCircle) view.findViewById(R.id.psychologist_list_bounce_circle);
        //recyclerView
        recyclerView = (RecyclerView) view.findViewById(R.id.psychologist_list_recycler_view);
        recyclerViewManager();
        getRosterPresenceChange(psychologists, roster, adapter);


        //添加服务器消息监听
        try {
            chatManager = ChatManager.getInstanceFor(connection);
            ChatListenerUtils.ChatListener chatListener = new ChatListenerUtils.ChatListener();
            chatManager.addChatListener(chatListener);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

        return view;
    }

    @Override
    public void onAttach(final Context context) {
        super.onAttach(context);
        this.context = context;
        intentFilter = new IntentFilter();
        //msgCome broadcast
//        intentFilter.addAction(NotifyComeBroadReceiver.NOTIFY_MSG_COME);
//        notifyComeBroadReceiver = new NotifyComeBroadReceiver();
//        context.registerReceiver(notifyComeBroadReceiver, intentFilter);
        //unread deal broadcast
        intentFilter.addAction(DealUnreadBroadReceiver.DEAL_UNREAD);
        dealUnreadBroadReceiver = new DealUnreadBroadReceiver(psychologists, thisuserName, adapter);
        context.registerReceiver(dealUnreadBroadReceiver, intentFilter);

        //处理消息的广播
        messageComeBroadReceiver = new MessageComeBroadReceiver();
        intentFilter.addAction(MessageComeBroadReceiver.MSG_COME);
        context.registerReceiver(messageComeBroadReceiver, intentFilter);
        messageComeBroadReceiver.setDealMsgListener(new MessageComeBroadReceiver.DealMsgListener() {
            @Override
            public void deal(String from, String body) {
                Log.d(TAG, "Psy deal: " + from + " " + body);
                //用于处理消息到来的notify
                Intent intent = new Intent(NotifyComeBroadReceiver.NOTIFY_MSG_COME);
                intent.putExtra("from", from);
                intent.putExtra("body", body);
                context.sendBroadcast(intent);
                //处理单人聊天返回后的未读气泡
                DealUnreadBubble(from);
            }
        });
    }

    @Override
    public void onDetach() {
        super.onDetach();
//        context.unregisterReceiver(notifyComeBroadReceiver);
        context.unregisterReceiver(dealUnreadBroadReceiver);
        context.unregisterReceiver(messageComeBroadReceiver);
    }

    private void DealUnreadBubble(String from) {
        int unread = 0;
        List<ComeMsgBean> comeMsgBeen = LitePalUtils.querryData(thisuserName, from);
        if (comeMsgBeen.size() == 0) {      //当没有这两者的消息记录
            unread = 1;
            LitePalUtils.addData(thisuserName, from, unread);
        } else {//当已经存在未读消息记录，读取原有的数量并+1
            for (ComeMsgBean comeMsgBeen1 : comeMsgBeen) {
                unread = comeMsgBeen1.getUnreadCount() + 1;
                LitePalUtils.updateData(unread, thisuserName, from);
            }
        }
        String user;
        int index;
        for (index = 0; index < psychologists.size(); index++) {
            user = psychologists.get(index).getUser().substring(0, psychologists.get(index).getUser().indexOf("@"));
            if (user.equals(from)) {    //判断所在list中的位置的用户和发送消息的用户是否一致
                psychologists.get(index).setUnreadCount(unread);        //设置未读消息数量
                PsychologistBean ps = psychologists.get(index);
                psychologists.remove(index);
                psychologists.add(index, ps);
                break;
            }
        }
        final int pos = index;
        Message message = new Message();
        message.what = UnreadBubble;
        message.arg1 = pos;
        handler.sendMessage(message);

    }

    class MyRefreshListener implements SwipeRefreshLayout.OnRefreshListener {        //swipeRefresh监听事件
        @Override
        public void onRefresh() {
            refreshList();
        }
    }

    private void refreshList() {
        PsychologyListAsyncTask.initPsychologists(connection, psychologists, roster, entries, thisuserName);
        Message message = new Message();
        message.what = ONREFRESH;
        handler.sendMessage(message);


    }

    private void recyclerViewManager() {

        //recyclerView
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecorationUtils(context, layoutManager.getOrientation()));
        //adapter
        if (connection != null) {
            PsychologyListAsyncTask.initPsychologists(connection, psychologists, roster, entries, thisuserName);
            adapter = new PsychologyAdapter(psychologists, thisuserName, circle);
            recyclerView.setAdapter(adapter);
            new Handler().postDelayed(new Runnable() {     //Handler实现延迟刷新UI
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                    progressDialog.dismiss();
                }
            }, 4000);        //延迟c
            recyclerView.scrollToPosition(psychologists.size() - 1);
        }
    }

    public void getRosterPresenceChange(final List<PsychologistBean> psychologists, final Roster roster, final PsychologyAdapter adapter) {       //监听entries的状态变化

        if (roster != null) {
            roster.addRosterListener(new RosterListener() {
                @Override
                public void entriesAdded(Collection<String> collection) {
                }

                @Override
                public void entriesUpdated(Collection<String> collection) {
                }

                @Override
                public void entriesDeleted(Collection<String> collection) {
                }

                @Override
                public void presenceChanged(Presence presence) {
                    final int offline = 0;
                    final int online = 1;
                    String status;
                    int statusColor;
                    String user;
                    String from;
                    if (presence.getStatus() == null) {
                        status = "离线";
                        statusColor = offline;
                    } else {
                        status = "在线";
                        statusColor = online;
                    }
                    from = presence.getFrom();
                    for (int index = 0; index < psychologists.size(); index++) {
                        user = psychologists.get(index).getUser();
                        if (user.substring(0, user.indexOf("@")).equals(from.substring(0, from.indexOf("@")))) {    //判断发生状态改变的用户在list中的位置
                            psychologists.get(index).setStatus(status);         //改变list中用户的状态
                            psychologists.get(index).setStatusColor(statusColor);
                            PsychologistBean ps = psychologists.get(index);
                            psychologists.remove(index);
                            if (status.equals("在线"))
                                psychologists.add(0, ps);        //实现最新登录的用户置顶
                            else
                                psychologists.add(psychologists.size(), ps);      //实现下线的用户置末
                            break;
                        }
                    }
                    Message message = new Message();
                    message.what = GET_PRESHENCE;
                    handler.sendMessage(message);
                }
            });
        }
    }

    public class DealUnreadBroadReceiver extends BroadcastReceiver {//单人聊天后，处理未读信息气泡
        private List<PsychologistBean> psychologists;
        private String thisuserName;
        private PsychologyAdapter adapter;

        public DealUnreadBroadReceiver(List<PsychologistBean> psychologists, String thisuserName, PsychologyAdapter adapter) {
            this.psychologists = psychologists;
            this.thisuserName = thisuserName;
            this.adapter = adapter;

        }

        //外部的param：
        //psychologists,thisuserName,adapter
        public static final String DEAL_UNREAD = "com.example.wwk.graduationpractice.DEAL_UNREAD";
        String user;
        String from;

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(DEAL_UNREAD)) {
                from = intent.getStringExtra("userJID");
                from = from.substring(0, from.indexOf("@"));
                LitePalUtils.deleteData(thisuserName, from);
                for (int index = 0; index < psychologists.size(); index++) {
                    user = psychologists.get(index).getUser();
                    user = user.substring(0, user.indexOf("@"));
                    if (from.equals(user)) {    //判断发生状态改变的用户在list中的位置
                        psychologists.get(index).setUnreadCount(0);     //返回后未读信息为0
                        PsychologistBean ps = psychologists.get(index);
                        psychologists.remove(index);
                        psychologists.add(index, ps);        //实现最新登录的用户置顶
                        break;
                    }
                }
                Message message = new Message();
                message.what=UnreadBroadReceiver;
                handler.sendMessage(message);


            }
        }
    }
}
